#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
# author: 小菠萝测试笔记
# blog:  https://www.cnblogs.com/poloyy/
# time: 2021/10/12 8:44 下午
# file: base.py
"""
from typing import Any, Generic, List, Optional, Type, TypeVar, Union

from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from sqlalchemy.orm import Session

from app.db.base_class import Base

ModelType = TypeVar("ModelType", bound=Base)
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)


class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
    def __init__(self, model: Type[ModelType]):
        """
        初始化
        :param model: ORM Model
        """
        self.model = model

    def get(self, db: Session, *, id: Any) -> Optional[ModelType]:
        """
        返回单条数据记录
        :param db: 数据库对象
        :param id: 记录id
        :return: ORM Model
        """
        return db.query(self.model).filter(self.model.id == id).first()

    def get_all(self, db: Session) -> Optional[List[ModelType]]:
        """
        返回所有记录
        :param db: 数据库对象
        :return: ORM Model List
        """
        return db.query(self.model).filter(self.model.is_delete != 1).all()

    def get_first_by_name(self, db: Session, *, name: str) -> Optional[ModelType]:
        """
        根据 name 获取数据
        :param db: 数据库对象
        :param name: 名字
        :return: None or ORM Model
        """
        return db.query(self.model).filter(self.model.name == name).first()

    def get_multi_by_name(
        self,
        db: Session,
        *,
        skip: int = 0,
        limit: int = 100,
        name: Optional[str] = None,
    ) -> Optional[List[ModelType]]:
        """
        翻页查询,支持模糊搜索
        :param db: 数据库对象
        :param skip: 跳过 skip 条数据
        :param limit: 返回记录数
        :param name: 名字
        :return: ORM Model List
        """
        filter_ = (self.model.is_delete != 1,)
        if name:
            filter_ = (self.model.name.like(f"%{name}%"), self.model.is_delete != 1)
        return db.query(self.model).filter(*filter_).offset(skip).limit(limit).all()

    def get_total_by_name(self, db: Session, *, name: Optional[str] = None) -> int:
        """
        统计记录数
        :param db: 数据库对象
        :param name: 名称
        :return: int
        """
        filter_ = (self.model.is_delete != 1,)
        if name:
            filter_ = (self.model.name.like(f"%{name}%"), self.model.is_delete != 1)
        return db.query(self.model).filter(*filter_).count()

    def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType:
        """
        添加数据
        :param db: 数据库对象
        :param obj_in: pydantic Model
        :return: ORM Model
        """
        obj_in_data = jsonable_encoder(obj_in)
        db_obj = self.model(**obj_in_data)
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    # 更新数据
    def update(
        self, db: Session, *, db_obj: ModelType, obj_in: Union[UpdateSchemaType]
    ) -> ModelType:
        """
        更新数据
        :param db: 数据库对象
        :param db_obj: ORM Model
        :param obj_in: Pydantic Model
        :return: ORM Model
        """
        obj_data = jsonable_encoder(db_obj)
        if isinstance(obj_in, dict):
            update_data = obj_in
        else:
            update_data = obj_in.dict(exclude_unset=True)
        for field in obj_data:
            if field in update_data:
                setattr(db_obj, field, update_data[field])
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    def delete(self, db: Session, *, id: int) -> Optional[ModelType]:
        """
        软删除
        :param db: 数据库对象
        :param id: 记录id
        :return: ORM Model
        """
        obj = db.query(self.model).get(id)
        if not hasattr(obj, "is_delete"):
            return None
        setattr(obj, "is_delete", 1)
        db.add(obj)
        db.commit()
        db.refresh(obj)
        return obj

    def true_delete(self, db: Session, *, id: int):
        """
        硬删除
        :param db: 数据库对象
        :param id: 记录id
        :return: ORM Model
        """
        obj = db.query(self.model).get(id)
        db.delete(obj)
        db.commit()
        return obj
